package android_serialport_api;

import android.util.Log;

import com.hck.weight_test.ObtainWeighing.WeightLogUtil;
import com.hck.weight_test.ObtainWeighing.interfaces.IDevice;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;

public class SerialPortDevice implements IDevice {
    private String path;
    private int baudrate;
    private int flags;
    private SerialPort serialPort;
    private InputStream inputStream;
    private OutputStream outputStream;

    public SerialPortDevice(String path, int baudrate, int flags) {
        this.path = path;
        this.baudrate = baudrate;
        this.flags = flags;
    }

    @Override
    public boolean open() {
        try {
            File file = new File(this.path);
            if (file.exists()) {
                this.serialPort = new SerialPort(file, this.baudrate, this.flags);
                this.inputStream = this.serialPort.getInputStream();
                this.outputStream = this.serialPort.getOutputStream();
                if (this.inputStream != null && this.outputStream != null) {
                    return true;
                }
            }
        } catch (Exception e) {
            WeightLogUtil.log("SerialPortDevice open: "+e);

        }

        return false;
    }

    @Override
    public boolean close() {
        try {
            if (this.inputStream != null) {
                this.inputStream.close();
                this.inputStream = null;
            }

            if (this.outputStream != null) {
                this.outputStream.close();
                this.outputStream = null;
            }

            if (this.serialPort != null) {
                this.serialPort.close();
                this.serialPort = null;
            }
            return true;
        } catch (Exception e) {
            WeightLogUtil.log("SerialPortDevice close:  "+e);
            return false;
        }
    }

    @Override
    public void write(byte[] buffer) {
        try {
            this.outputStream.write(buffer);
            this.outputStream.flush();
        } catch (Exception e) {
            WeightLogUtil.log("SerialPortDevice write: "+e);
        }
    }

    @Override
    public int read(byte[] buffer) {
        try {
            return this.inputStream.available() > 0 ? this.inputStream.read(buffer) : 0;
        } catch (IOException e) {
            WeightLogUtil.log("SerialPortDevice read: "+e);
            return -1;
        }
    }
}
